import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, data) => {
    state.userInfo = data
  }
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    console.log(res)
    commit('SET_TOKEN', res.token)
    setToken(res.token)
  },
  // get user info
  async getInfo(ctx) {
    const res = await getInfo()
    console.log(res)
    ctx.commit('SET_USERINFO', res.userInfo)
    return res
  },

  // user logout
  logout({ commit, state }) {
    removeToken()
    resetRouter(0)
    commit('RESET_STATE')
    commit('permission/setRoute', [], { root: true })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

